package com.tongguan.paypos.activity.trans;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;

import com.tongguan.paypos.R;
import com.tongguan.paypos.adapter.RechargeAdapter;
import com.tongguan.paypos.base.BaseActivity;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.EditInputFilter;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.CreateOrderInfo;
import com.tongguan.paypos.entity.PayInfo;
import com.tongguan.paypos.entity.TransInfo;
import com.tongguan.paypos.fragment.ResultHYCFragment;
import com.tongguan.paypos.utils.CipherUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.NumberUtils;
import com.tongguan.paypos.utils.SPUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.utils.Utils;
import com.tongguan.paypos.view.CustomAlertDialog;
import com.tongguan.paypos.view.CustomProgressDialog;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

public class MemberRechargeActivity extends BaseActivity {

    private static final int REQUEST_RECHARGE = 10020;
    private static final int REQUEST_RECHARGE_WX_PAY = 10030;
    private static final int DELAYED_TIME = 5000;//

    @BindView(R.id.et_card_no)
    EditText mEtCardNo;
    @BindView(R.id.et_amount)
    EditText mEtAmount;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.btnRecharge)
    Button mBtnRecharge;
    @BindView(R.id.btn_scan_qr)
    Button mBtnScanQr;

    private RechargeAdapter adapter;
    private double amount; //金额
    private ArrayList<Double> mData;
    private boolean isStatus = false;
    private String orderId;
    private int count = 3;//查询次数
    private String cardNo;
    private int count_sync = 3;//同步查询次数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_recharge);
        ButterKnife.bind(this);
        initTile(R.string.title_member, true);
        mData = new ArrayList<>();
        mData.add(50.0);
        mData.add(100.0);
        mData.add(200.0);
        mData.add(300.0);
        mData.add(500.0);
        mData.add(1000.0);
        mData.add(2000.0);
        mData.add(3000.0);
        mData.add(5000.0);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.setAdapter(adapter = new RechargeAdapter());
        adapter.replaceAll(mData);
        initEvent();

    }

    private void initEvent() {
        mBtnScanQr.setOnClickListener(v -> startActivityForResult(new Intent(context, CaptureActivity.class), REQUEST_RECHARGE));
        InputFilter[] filter = {new EditInputFilter(context)};
        mEtAmount.setFilters(filter);
        adapter.setOnItemClickListener((view, position) -> {
            isStatus = true;
            if (position >= 0) {
                amount = mData.get(position);
                mEtAmount.setText(String.valueOf(amount));
            } else {
                amount = 0;
                mEtAmount.setText("");
            }
            isStatus = false;
        });
        mBtnRecharge.setOnClickListener(v -> {
            cardNo = mEtCardNo.getText().toString();
            String amount = mEtAmount.getText().toString();
            if (TextUtils.isEmpty(cardNo)) {
                ToastUtils.showCustom(context, "请输入会员卡号");
                return;
            }
            if (TextUtils.isEmpty(amount)) {
                ToastUtils.showCustom(context, "请输入充值金额");
                return;
            }
            recharge();
        });
        mEtAmount.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!isStatus) {
                    adapter.replaceItemClickListener();
                }
                if (s.length() > 0) {
                    amount = Double.valueOf(s.toString());
                }
            }
        });
    }

    private void recharge() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(amount));//单位元
        RequestCallback.post(context, UrlConstants.CREATE_ORDER, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                CreateOrderInfo createOrder = CreateOrderInfo.objectFromData(response);
                if (createOrder.getStatus() != 100) {
                    ToastUtils.showCustom(context, createOrder.getMessage());
                    return;
                }
                orderId = createOrder.getOrderId();
                Intent intent = new Intent(context, CaptureActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("title", "微信充值");
                bundle.putString("money", NumberUtils.getMoneyTypeIgnore(amount));
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_RECHARGE_WX_PAY);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode = " + requestCode + " resultCode = " + resultCode);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            //线上支付
            if (requestCode == REQUEST_RECHARGE) {
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEtCardNo.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    L.d("解析二维码失败");
                }
            }
            if (requestCode == REQUEST_RECHARGE_WX_PAY) {
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    wxRecharge(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    L.d("解析二维码失败");
                }
            }
        }
    }

    private void wxRecharge(String result) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        params.put(UrlConstants.KEY_COUPON_MONEY, 0);
        params.put(UrlConstants.KEY_COUPON_INFO, "");
        params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(amount));
        params.put(UrlConstants.KEY_CARD_NO, cardNo);
        params.put(UrlConstants.KEY_AUTH_CODE, result);
//        params.put(UrlConstants.KEY_NONCE_STR, Utils.getRand32());
//        params.put(UrlConstants.KEY_SIGN,signKey(params));
        RequestCallback.post(context, UrlConstants.MEMBER_RECHARGE, params, mDialog, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                String message = payInfo.getMessage();
                if (payInfo.getStatus() != 100) {
                    if (AppConstants.messageFilter(message)) { //用户问题拦截
                        new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, (dialog, which) -> finish())
                                .show();
                        return;
                    }
                    ToastUtils.showCustom(context, message);
                    //查询上游 订单
                    queryOder(message);
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    //查询上游 订单
                    queryOder(message);
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                successJumpAct(transInfo);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                queryOder("支付网络异常");
            }
        });
    }

    /**
     * 查询上游订单接口
     *
     * @param msg 状态
     */
    private void queryOder(String msg) {
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.setLoadingMessage(msg + "\n正在查询，请稍等...");
            mDialog.show();
        }
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
//        params.put(UrlConstants.KEY_NONCE_STR, Utils.getRand32());
//        params.put(UrlConstants.KEY_SIGN,signKey(params));
        RequestCallback.post(context, UrlConstants.QUERY_ORDER, params, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                String message = payInfo.getMessage();
                if (payInfo.getStatus() != 100) {
                    //查询状态还是失败 继续查询
                    if (AppConstants.messageFilter(message)) { // 问题拦截
                        new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, null)
                                .show();
                        return;
                    }
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    //查询上游 订单
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                if (mDialog != null) {
                    mDialog.dismiss();
                }
                successJumpAct(transInfo);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mHandler.sendMessageDelayed(mHandler.obtainMessage(0, "查询订单网络异常"), DELAYED_TIME);
            }
        });
    }

    private void queryOderDetail() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(context, UrlConstants.ORDER_DETAILS + orderId, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                if (payInfo.getStatus() != 100) {
                    ToastUtils.showCustom(context, payInfo.getMessage());
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    new CustomAlertDialog.Builder(context).setTitle(R.string.common_tip_title)
                            .setMessage(payInfo.getMessage() + "\n订单详情查询失败，是否重新请求")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> queryOderDetail())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    return;
                }
                if (!"0".equals(transInfo.getState())) {
                    //防止数据查询接口和订单详情接口没同步
                    if (mDialog != null && !mDialog.isShowing()) {
                        mDialog.show();
                        mDialog.setLoadingMessage("详情状态错误，重新查询...");
                    }
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(1, ""), DELAYED_TIME);
                }
                L.d("订单成功");
                //成功跳转
                successJumpAct(transInfo);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                new CustomAlertDialog.Builder(context).setTitle(R.string.error_net)
                        .setMessage(e.getMessage())
                        .setPositiveButton("重新加载", (dialog, which) -> queryOderDetail())
                        .setNegativeButton(R.string.common_cancel, null).show();
            }
        });
    }

    private void successJumpAct(TransInfo info) {
        Bundle bundle = new Bundle();
        bundle.putString(ResultManageActivity.EXCHANGE_FRAGMENT_NAME, ResultHYCFragment.class.getName());
        bundle.putParcelable(ResultHYCFragment.EXCHANGE_RESULT, info);
        bundle.putString(ResultHYCFragment.EXCHANGE_CARD_NO, cardNo);
        jumpAct(ResultManageActivity.class, bundle, false, true);
    }

    //延时
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isFinishing()) {
                switch (msg.what) {
                    case 0:
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        String message = (String) msg.obj;
                        if (count > 0) {
                            queryOder(message);
                            count--;
                        } else {
                            new CustomAlertDialog.Builder(context).setTitle("支付失败")
                                    .setMessage(message)
                                    .setPositiveButton("再次查询", (dialog, which) -> queryOder(message))
                                    .setNegativeButton("取消订单", (dialog, which) -> finish()).show();
                        }
                        break;
                    case 1:
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        if (count_sync > 0) {
                            queryOderDetail();
                            count_sync--;
                        } else {
                            new CustomAlertDialog.Builder(context).setTitle("支付失败")
                                    .setMessage("订单数据不对")
                                    .setPositiveButton("再次查询", (dialog, which) -> queryOderDetail())
                                    .setNegativeButton("取消订单", (dialog, which) -> finish()).show();
                        }
                        break;
                }
            }
        }
    };

    //签名
    private String signKey(Map map){
        String key = (String) SPUtils.getSp(context, AppConstants.SIGNATURE, "");
        return CipherUtils.Signature(map,key);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RequestCallback.cancelAllRequest();
        mHandler.removeMessages(0);
    }
}
